﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.EntityValidation
{
    public  class DbValidationAttribute : ValidationAttribute
    {

        public static void Init(string conn)
        {

            ConnetionStringCommon = conn;
        }
        public string ConnetionString { get; set; }
        public static string ConnetionStringCommon { get; set; }
        public string Sql { get; set; }
        public DbValidationAttribute()
        {
            ErrorMessage = "{0}不存在";
        }
        public override bool Verify(object o)
        {

            string conn = ConnetionString ?? ConnetionStringCommon;

            if (string.IsNullOrWhiteSpace(Sql))
            {
                throw new Exception("参数Sql不可为空");
            }
            if (string.IsNullOrWhiteSpace(conn))
            {

                throw new Exception("连接字符串不可为空");
            }

            SqlConnection connection = new SqlConnection(conn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = connection;

            try
            {
                connection.Open();
                cmd.CommandText = string.Format(Sql, o);

                
                    cmd.Parameters.Add(new SqlParameter($"@{Name}", o??""));
                
                var da = new SqlDataAdapter(cmd);
                var dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }
    }
}